import store from '../store/store.js'

let socketTask = null;
let reconnectTimer = null;
let MAX_RECONNECT_ATTEMPTS = 5;
let reconnectAttempts = 0;

export const connectWebSocket = () => {
  const employeeId = store.state.m_user.employeeInfo.employeeId
  const token = store.state.m_user.token
  socketTask = uni.connectSocket({
    url: `wss://linchaochao.com:8443/api/ws/messages?employeeId=${encodeURIComponent(employeeId)}&token=${encodeURIComponent(token)}`,
    success: () => {
      console.log('websocket连接创建成功')
    },
    fail: (err) => {
      console.log('webSocket连接创建失败:', err)
      scheduleReconnect()
    }
  });
  socketTask.onOpen(() => {
    console.log('WebSocket连接已建立');
    // 发送连接确认消息
    socketTask.send({
      data: JSON.stringify({
        type: 'JOIN',
        content: '用户已连接'
      }),
      success: () => console.log('JOIN消息发送成功'),
      fail: (err) => console.error('消息发送失败:', err)
    });
  });
  // 监听消息接收
  socketTask.onMessage((res) => {
    console.log('接收到消息了')
    const message = res.data;    console.log('接收到的消息是',message)
    uni.$emit('refreshMessageList', { resetPage: true });
  });

  // 监听连接关闭，这里进行全局方法的移除d
  socketTask.onClose(() => {
    console.log('WebSocket连接已关闭');
    scheduleReconnect();
  });

  // 监听错误事件
  socketTask.onError((err) => {
    console.error('WebSocket错误:', err);
    socketTask.close({
      code: 1006
    });
  });

}

// 定时重连逻辑
const scheduleReconnect = () => {
  if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS) return uni.showToast({
    title: '已经重试很多次了，请稍后再试',
    icon: 'none'
  })
  if (reconnectTimer) clearTimeout(reconnectTimer)
  reconnectTimer = setTimeout(() => {
    console.log('尝试重新连接...');
    connectWebSocket();
    reconnectAttempts++;
  }, 5000);
}

// 关闭连接,这是扩展接口
const closeWebSocket = () => {
  if (socketTask) {
    socketTask.close({
      reason: 'manual close'
    });
    socketTask = null;
  }
  if (reconnectTimer) clearTimeout(reconnectTimer);
}